package com.yuqian.talkservers;


import com.google.gson.Gson;
import com.yuqian.bean.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TCPClient {
    Logger log= LoggerFactory.getLogger(TCPClient.class);
    Gson gson=new Gson();
    public static void out(String info){
        System.out.println(info);
    }
    static private Socket clientSocket;

    public TCPClient() {}

    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        String serverIP;
        clientSocket = new Socket("116.196.82.199", 6789);
        TCPClient client = new TCPClient();
        client.start();
    }

    public void start() {
        try {
            Scanner scanner = new Scanner(System.in);
            setName(scanner);
            log.info("姓名设置完毕");
        //    out("姓名设置完毕");
            // 接收服务器端发送过来的信息的线程启动  
            ExecutorService exec = Executors.newCachedThreadPool();
            exec.execute(new ListenrServser());

            // 建立输出流，给服务端发信息  
            PrintWriter pw = new PrintWriter(
                    new OutputStreamWriter(clientSocket.getOutputStream(), "UTF-8"), true);
            log.info("输出流已创建");
;
            Message message=new Message();
            message.setId(2);
            message.setMessage("message");
            message.setFromwhere("二傻");
            message.setTowhere("1");
            message.setMessageType("user");
            message.setDeviceType("PC");

            while(true) {

                message.setContent(scanner.nextLine());
                pw.println(gson.toJson(message));
                //pw.write(gson.toJson(message));
              //  pw.println(gson.toJson(message));

            }
        } catch(Exception e) {

         log.error("出现异常"+e);
            e.printStackTrace();
        } finally {
            if (clientSocket !=null) {
                out("断开了链接");
                try {
                    clientSocket.close();
                } catch(IOException e) {
                   // out("what's worng"+e);
                    e.printStackTrace();
                }
            }
        }
    }

    private void setName(Scanner scan) throws Exception {
        String name;
        //创建输出流
        PrintWriter pw = new PrintWriter(
                new OutputStreamWriter(clientSocket.getOutputStream(), "UTF-8"),true);
        //创建输入流
        BufferedReader br = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream(),"UTF-8"));

        while(true) {
           log.info("正在创建连接");
            Gson gson=new Gson();
            Message message=new Message();
            message.setId(2);
            message.setMessage("login");
            message.setTowhere("1");
            message.setFromwhere("2");
            message.setDeviceType("PC");
            pw.println(gson.toJson(message));
          //  out(gson.toJson(message));
        //    pw.flush();

            Message message1=gson.fromJson(br.readLine(),Message.class);
            if (message1.getMessage().equals("systemmessage")){
                out("【系统消息】"+"："+message1.getContent());
            }
            break;
        }
    }



    // 循环读取服务端发送过来的信息并输出到客户端的控制台  
    class ListenrServser implements Runnable {


        public void run() {

            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));

                String msgString;
                while((msgString = br.readLine())!= null) {

                    Message message=gson.fromJson(msgString,Message.class);
                    if (message.getMessage().equals("offOnline")){
                        System.out.println(message.getContent());
                        System.exit(0);
                    }else if (message.getMessage().equals("systemmessage")){
                        out("【系统消息】:"+message.getContent());
                    }else if (message.getMessage().equals("message")){
                        out(message.getFromwhere()+":"+message.getContent());
                    }else if (message.getMessage().equals("userOnlie")){
                        out("【系统消息】:"+message.getContent());
                    }

                }
            } catch(Exception e) {
                out("监听异常");
                e.printStackTrace();
            }
        }
    }

    public void getOffOnlineMessage(String userId){

    }


}  